<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="用户名称" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入用户名称"
              clearable
              size="small"
              style="width: 220px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 220px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="queryParams.email"
              placeholder="请输入邮箱"
              clearable
              size="small"
              style="width: 220px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="用户状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="选择部门" class="form">
            <treeselect
              @select="handleNodeClick"
              style="width: 300px"
              :clearable="false"
              :options="loadOptions"
              :disable-branch-nodes="false"
              :show-count="true"
              placeholder="请选择部门"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              class="btn"
              type="cyan"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
              >新增</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:user:edit']">修改</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:user:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5"></el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
          width="100%"
          @sort-change="sort_change"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="用户名称"
            align="center"
            prop="userName"
            width="150"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span class="blue" @click="handleUpdate(scope.row)">{{
                scope.row.userName
              }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="手机号码"
            prop="phonenumber"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.phonenumber }}</span>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="短信验证" align="center" width="100">
            <template slot-scope="scope">
              <span class="yellow" v-if="scope.row.verify==0">未验证</span>
              <span class="blue" v-if="scope.row.verify==1">已验证</span>
              <span class="red" v-if="scope.row.verify==2">已经关闭</span>
            </template>
          </el-table-column> -->
          <el-table-column
            prop="customrCount"
            label="客户数量"
            align="center"
            width="150"
            :show-overflow-tooltip="true"
            sortable
          >
            <template slot-scope="scope">
              <!-- <span class="blue" @click="handleCustomer(scope.row)">{{
                scope.row.customrCount
              }}</span> -->
              <span>{{ scope.row.customrCount }}</span>
            </template>
          </el-table-column>

          <el-table-column label="业务类型" align="center" width="150">
            <template slot-scope="scope">
              <span>{{ formatType(scope.row.businessType) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="统计类型" align="center" width="120">
            <template slot-scope="scope">
              <span>{{ formatTongji(scope.row.statisticsType) }}</span>
            </template>
          </el-table-column>
          <!-- :formatter="stateFormat" -->
          <el-table-column
            label="管理国家"
            prop="country"
            align="center"
            width="110"
            :show-overflow-tooltip="true"
          >
          <template slot-scope="{row}">
            <span>{{row.continent}} <span v-if="row.country">-</span> {{row.country}}</span>
          </template>
          </el-table-column>
          <el-table-column
            label="一季度"
            width="150"
            align="center"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span
                >{{
                  finishRate(
                    scope.row.finishTargetAmount,
                    scope.row.targetAmount
                  )
                }}%</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="二季度"
            align="center"
            width="150"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span
                >{{
                  finishRate(
                    scope.row.finishSecondQuarteraMount,
                    scope.row.secondQuarteraMount
                  )
                }}%</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="三季度"
            align="center"
            width="150"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span
                >{{
                  finishRate(
                    scope.row.finishThirdlyQuarteraMount,
                    scope.row.thirdlyQuarteraMount
                  )
                }}%</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="四季度"
            align="center"
            width="150"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span
                >{{
                  finishRate(
                    scope.row.finishFourthlyQuarteraMount,
                    scope.row.fourthlyQuarteraMount
                  )
                }}%</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="年度进度"
            align="center"
            width="150"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <!-- <el-progress
                :text-inside="true"
                :stroke-width="26"
                :percentage="finishYearRate(1,1,1,1,2,2,2,2)"
              ></el-progress> -->
              <span
                >{{
                  finishYearRate(
                    scope.row.finishTargetAmount,
                    scope.row.finishSecondQuarteraMount,
                    scope.row.finishThirdlyQuarteraMount,
                    scope.row.finishFourthlyQuarteraMount,
                    scope.row.targetAmount,
                    scope.row.secondQuarteraMount,
                    scope.row.thirdlyQuarteraMount,
                    scope.row.fourthlyQuarteraMount
                  )
                }}%</span
              >
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="部门"
            align="center"
            prop="dept.deptName"
            width="100"
            :show-overflow-tooltip="true"
          /> -->
          <el-table-column
            label="邮箱"
            align="center"
            prop="email"
            width="160"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="用户状态" align="center" width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>-->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="190"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-key"
                @click="handleResetPwd(scope.row)"
                v-hasPermi="['system:user:resetPwd']"
                >重置</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleRemove(scope.row)"
                v-hasPermi="['system:user:remove']"
                >解除钉钉</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="form.phonenumber"
                placeholder="请输入手机号码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect
                v-model="form.deptId"
                :clearable="false"
                :disable-branch-nodes="false"
                :options="loadOptions"
                :show-count="true"
                :disabled="typeModify == 1"
                placeholder="请选择归属部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row> </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input
                :disabled="typeModify == 1"
                v-model="form.userName"
                placeholder="请输入用户名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.userId == undefined">
            <el-form-item label="用户密码" prop="password">
              <el-input
                :disabled="typeModify == 1"
                v-model="form.password"
                placeholder="请输入用户密码"
                type="password"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色" prop="roleIds">
              <el-select
                :disabled="typeModify == 1"
                v-model="form.roleIds"
                multiple
                placeholder="请选择"
                filterable
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group :disabled="typeModify == 1" v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  >{{ dict.dictLabel }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业务类型" prop="businessType">
              <el-select v-model="form.businessType">
                <el-option
                  v-for="item in levelList2"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统计类型" prop="statisticsType">
              <el-select v-model="form.statisticsType">
                <el-option
                  v-for="item in statisticsTypeOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.businessType==1">
          <el-col :span="12">
            <el-form-item label="洲别:" prop="continent">
              <!-- <el-cascader
               v-model="form.continent"
                :props="defaultParams"
                :options="countryData"
                clearable
              ></el-cascader> -->
              <el-select
                v-model="form.continent"
                placeholder="请选择洲"
                clearable
                filterable
                multiple
                @change="search"
              >
                <el-option
                  v-for="item in continentlist"
                  :key="item.label"
                  :label="item.label"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理国家" prop="country">
              <!-- @change="search" -->
              <el-select
                v-model="form.country"
                multiple
                placeholder="请选择国家"
                clearable
                filterable
              >
                <el-option
                  v-for="item in countryList"
                  :key="item.id"
                  :label="item.country"
                  :value="item.country"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="周报填写">
              <!-- <el-radio v-model="form.writes" :label="0">否</el-radio>
              <el-radio v-model="form.writes" :label="1">是</el-radio> -->
              <el-select v-model="form.writes" clearable placeholder="请选择">
                <el-option label="否" :value="0"></el-option>
                <el-option label="是" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="一季度目标" prop="targetAmount">
              <el-input
                v-model="form.targetAmount"
                placeholder="请输入一季度目标"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二季度目标" prop="secondQuarteraMount">
              <el-input
                v-model="form.secondQuarteraMount"
                placeholder="请输入二季度目标"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="三季度目标" prop="thirdlyQuarteraMount">
              <el-input
                v-model="form.thirdlyQuarteraMount"
                placeholder="请输入三季度目标"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="四季度目标" prop="fourthlyQuarteraMount">
              <el-input
                v-model="form.fourthlyQuarteraMount"
                placeholder="请输入四季度目标"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属主体">
              <el-select
                v-model="form.mainBody"
                placeholder="请选择所属主体"
                clearable
                style="width: 258px"
              >
                <el-option
                  v-for="dict in bodyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                :disabled="typeModify == 1"
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox
            v-model="upload.updateSupport"
          />是否更新已经存在的用户数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate"
            >下载模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 月度统计弹窗 -->
    <el-dialog
      title="通话记录柱状图"
      :close-on-click-modal="true"
      :visible.sync="dialog8"
      width="1000px"
    >
      <div class="schart-box">
        <div class="block">
          <span class="demonstration" style="margin-right: 10px"
            >选择查看月份</span
          >
          <el-date-picker
            v-model="value00"
            type="month"
            format="yyyy-MM"
            value-format="yyyy-MM"
            @change="bindGetTime"
            placeholder="选择年月"
          ></el-date-picker>
        </div>
        <div id="myChart" :style="{ height: '500px', width: '100%' }" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  updateUser2,
  exportUser,
  resetUserPwd,
  changeUserStatus,
  importTemplate,
  timeMonth,
  searchTime8,
  companyGet,
  company,
  recorder,
  removeUser,
  CountryList,
  getCountry
} from "@/api/system/user";
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Schart from "vue-schart";
import Template from '../../sample/template.vue';
export default {
  name: "User",
  components: { Treeselect },
  // SchartTemplate
  data() {
    return {
      // 分类
      defaultParams: {
        label: "continent",
        value: "continent",
        children: "countries",
        multiple: true,
        checkStrictly: true
      },
      countryList: [], //国家
      countryData: [],
      percent: 70,
      typeModify: undefined,
      // 绑定公司
      dialog10: false,
      query: {
        companyName: "",
        phone: ""
      },
      continentlist: [
        {
          value: "亚洲",
          label: "亚洲"
        },
        {
          value: "北美洲",
          label: "北美洲"
        },
        {
          value: "南美洲",
          label: "南美洲"
        },
        {
          value: "大洋洲",
          label: "大洋洲"
        },
        {
          value: "欧洲",
          label: "欧洲"
        },
        {
          value: "非洲",
          label: "非洲"
        }
      ],
      levelList2: [
        {
          id: "2",
          title: "国内"
        },
        {
          id: "1",
          title: "国外"
        }
      ],
      statisticsTypeOptions: [
        {
          id: "1",
          title: "金额"
        },
        {
          id: "2",
          title: "容量"
        },
        {
          id: "3",
          title: "金额/容量"
        }
      ],
      companyInfo: {},
      valueCompang: "",
      companyList: [],
      companyId: null,
      // 监听
      radio1: "手机坐席",
      userId: 0,
      pageSize: 5,
      page: 1,
      todelpage: 0,
      listenlists: [],
      dialog6: false,
      dialog7: false,
      dialog8: false,
      value888: "",
      options888: [
        {
          value: "",
          label: "全部"
        },
        {
          value: "1",
          label: "接通"
        },
        {
          value: "60",
          label: "大于1分钟"
        },
        {
          value: "120",
          label: "大于2分钟"
        }
      ],
      audio: "",
      name: "",
      // 柱状图
      value00: "",
      month: 0,
      dialog8: false,
      row888: {},
      data8: [],
      monthTime666: [],
      moneyTime666: [],
      callTime666: [],
      moneyCount666: [],
      callCount666: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      loadOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      statusOptions2: [
        { value: "1", label: "开通" },
        { value: "0", label: "不开" }
      ],
      statusOptions3: [
        { value: "0", label: "PC端" },
        { value: "1", label: "APP端" }
      ],
      // 性别状态字典
      sexOptions: [],
      bodyOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        // country: ""
        // continent:[]
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: undefined,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },

      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        // nickName: [
        //   { required: true, message: "用户昵称不能为空", trigger: "blur" },
        // ],
        roleIds: [{ required: true, message: "请选择角色", trigger: "blur" }],
        deptId: [
          { required: true, message: "归属部门不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" }
        ],
        statisticsType: [
          { required: true, message: "请选择统计类型", trigger: "blur" }
        ],
        targetAmount: [
          { required: true, message: "请填写一季度目标", trigger: "blur" }
        ],
        secondQuarteraMount: [
          { required: true, message: "请填写二季度目标", trigger: "blur" }
        ],
        thirdlyQuarteraMount: [
          { required: true, message: "请填写三季度目标", trigger: "blur" }
        ],
        fourthlyQuarteraMount: [
          { required: true, message: "请填写四季度目标", trigger: "blur" }
        ],
        businessType: [
          { required: true, message: "请选择业务类型", trigger: "blur" }
        ],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        // country: [
        //   { required: true, message: "请选择管理国家", trigger: "blur" }
        // ],
        // phonenumber: [
        //   { required: true, message: "手机号码不能为空", trigger: "blur" }
        // ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    $route(to, from) {
      console.log(to.path);
      console.log(from.path);
      if (
        from.path == "/company" &&
        to.path == "/system/user" &&
        this.$route.params.id
      ) {
        console.log(this.$route.params.id, "跳转过来的公司id");
        this.queryParams.companyId = this.$route.params.id;
        console.log(this.queryParams, "-------------");
        this.getList();
      }
    }
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
      console.log(this.statusOptions);
    });
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getDicts("main_body_code").then(response => {
      this.bodyOptions = response.data;
    });
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  mounted() {
    var date = new Date();
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    this.month = y + "-" + m;
    this.getTreeselect();
    // this.getCountry();
  },
  methods: {
    // // 获取国家列表
    // getCountry() {
    //   getCountry().then(response => {
    //     console.log(response);
    //     this.countryData = response.rows;
    //   });
    // },

    // 露露
    search() {
      console.log(this.form.continent);
      let str = this.form.continent.join(",");
      this.getCountryList(str);
    },
    // 获取国家列表
    getCountryList(str) {
      console.log(4444,str);
      let query = {
        continent: str
      };
      CountryList(query).then(response => {
        this.countryList = response.rows;
        console.log(888);
      });
    },
    stateFormat(row, column, cellValue) {
      console.log(777, cellValue);
      if (!cellValue) return "";
      if (cellValue.length > 10) {
        //最长固定显示10个字符
        return cellValue.slice(0, 10) + "...";
      }
      return cellValue;
    },
    // 露
    finishRate(v1, v2) {
      if (v1 / v2 > 0) {
        return ((v1 / v2) * 100).toFixed(2);
      } else {
        return 0;
      }
    },
    finishYearRate(v1, v2, v3, v4, v5, v6, v7, v8) {
      let get = v1 + v2 + v3 + v4;
      let all = v5 + v6 + v7 + v8;
      if (get / all > 0) {
        return Number(((get / all) * 100).toFixed(2));
      } else {
        return 0;
      }
    },
    formatType(val) {
      var str = this.levelList2.find(function(item) {
        return item.id == val;
      });
      if (str) return str.title;
    },
    formatTongji(val) {
      var str = this.statisticsTypeOptions.find(function(item) {
        return item.id == val;
      });
      if (str) return str.title;
    },
    // 用于排序方法
    sort_change(column, prop, order) {
      console.log(column);
    },
    checkPermi,
    checkRole,
    muiscPlay55(index, row) {
      console.log(row);
      if (row.recordFileDownloadUrl) {
        this.listenlists[index].isDownload = "1";
      } else {
        this.$message.error(`录音暂未同步`);
      }
    },
    handleCustomer(row) {
      console.log(row);
      let type9 = localStorage.getItem("type9");
      if (type9 == 0) {
        console.log("跳资质");
        this.$router.push({
          name: "Customer",
          params: {
            userName: row.userName
          }
        });
      } else if (type9 == 1) {
        this.$router.push({
          name: "CustomerManagement_zizhi",
          params: {
            userName: row.userName
          }
        });
        console.log("跳普通");
      }
    },
    recordAdmin() {
      this.$router.push({
        path: "/recordAdmin"
      });
    },
    companyGet() {
      companyGet({
        pageNum: 1,
        pageSize: 100000000000000000000000000,
        companyName: this.query.companyName,
        phone: this.query.phone
      }).then(res => {
        console.log(res, "公司列表");
        this.companyList = res.rows;
      });
    },
    companyChoose(e) {
      console.log(e);
      this.companyId = e;
    },
    company(index, row) {
      console.log(row);
      this.dialog10 = true;
      this.companyInfo = row;
      this.valueCompang = row.companyName;
      this.companyId = row.companyId;
      this.companyGet();
    },
    submitCompany() {
      if (this.companyId) {
        company({
          compyId: this.companyId,
          userId: this.companyInfo.userId
        }).then(res => {
          this.$message.success(`绑定成功`);
          this.dialog10 = false;
          this.getList();
        });
      } else {
        this.$message.error(`请选择公司`);
      }
    },
    //   监听操作
    muiscPlay1(index, row) {
      console.log(row);
      if (row.recordFileDownloadUrl) {
        this.audio = row.recordFileDownloadUrl;
        this.listenlists[index].isHear = "1";
        this.dialog7 = true;
      } else {
        this.$message.error(`录音暂未同步`);
      }
      // recorder(row.id).then((res)=>{
      //   console.log(res)
      // })
    },
    quxiao666() {
      this.dialog6 = false;
    },
    radio(e) {
      console.log(e, "用于切换");
    },
    searchTime() {
      this.page = 1;
      console.log(this.value888);
      searchTime8({
        pageSize: 15,
        pageNum: this.page,
        mobile: this.row.phonenumber,
        callTime: this.value888
      }).then(res => {
        console.log(res);
        this.listenlists = res.rows;
        this.todelpage = res.total;
      });
    },
    //   监听分页
    handleCurrentChange22(e) {
      console.log(e);
      this.page = e;
      searchTime8({
        pageSize: 15,
        pageNum: this.page,
        mobile: this.row.phonenumber,
        callTime: this.value888
      }).then(res => {
        console.log(res);
        this.listenlists = res.rows;
        this.todelpage = res.total;
      });
    },
    //   监听操作
    handleListen(index, row) {
      this.dialog6 = true;
      this.row = row;
      this.name = row.userName;
      this.page = 1;
      console.log(this.row);
      searchTime8({
        pageSize: 15,
        pageNum: this.page,
        mobile: this.row.phonenumber,
        // mobile: '1',
        callTime: this.value888
      }).then(res => {
        console.log(res);
        this.listenlists = res.rows;
        this.todelpage = res.total;
      });
    },
    drawLineData() {
      // 基于准备好的dom，初始化echarts实例
      let myChart = this.$echarts.init(document.getElementById("myChart"));
      // 绘制图表
      myChart.setOption({
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "none"
          },
          padding: [5, 10]
        },
        // toolbox: {
        //   // 用于图表切换
        //     feature: {
        //         dataView: {show: true, readOnly: false},
        //         magicType: {show: true, type: ['line', 'bar']},
        //         restore: {show: true},
        //         saveAsImage: {show: true}
        //     }
        // },
        legend: {
          data: ["有效通话时长", "消耗时长", "有效拨打次数", "拨打总次数"]
        },
        grid: {
          left: 20,
          right: 20,
          bottom: 0,
          top: 50,
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            data: this.monthTime666,
            axisPointer: {
              type: "shadow"
            },
            // 去掉刻度
            // boundaryGap: false,
            axisTick: {
              show: false
            },
            // 间隔显示
            axisLabel: {
              interval: 1
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            name: "时间(分钟)",
            splitNumber: 10,
            axisLabel: {
              formatter: "{value}"
            },
            splitLine: {
              show: false //去掉网格线
            }
          },
          {
            type: "value",
            name: "拨打次数(次)",
            splitNumber: 10,
            axisLabel: {
              formatter: "{value}"
            },
            splitLine: {
              show: false //去掉网格线
            }
          }
        ],
        series: [
          {
            name: "有效通话时长",
            type: "bar",
            yAxisIndex: 0,
            data: this.callTime666
          },
          {
            name: "消耗时长",
            type: "bar",
            yAxisIndex: 0,
            data: this.moneyTime666
          },
          {
            name: "有效拨打次数",
            type: "line",
            yAxisIndex: 1,
            data: this.moneyCount666
          },
          {
            name: "拨打总次数",
            type: "line",
            yAxisIndex: 1,
            data: this.callCount666
          }
        ]
      });
    },
    bindGetTime(e) {
      console.log(e);
      this.month = e;
      if (this.month == null) {
        var date = new Date();
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? "0" + m : m;
        this.month = y + "-" + m;
      }
      timeMonth({
        userId: this.row888.userId,
        time: this.month
      }).then(res => {
        console.log(res);
        this.data8 = res.data;
        let arr1 = [];
        let arr2 = [];
        let arr3 = [];
        let arr4 = [];
        let arr5 = [];
        for (let i = 0; i < this.data8.length; i++) {
          //   arr1.push(this.data8[i].time.slice(8,10));
          arr1.push(this.data8[i].createTime);
          arr2.push(this.data8[i].callAllMinute);
          arr3.push(this.data8[i].callUseMinute);
          arr4.push(this.data8[i].callUseTime);
          arr5.push(this.data8[i].callAllTime);
        }
        this.monthTime666 = arr1;
        this.moneyTime666 = arr2;
        this.callTime666 = arr3;
        this.moneyCount666 = arr4;
        this.callCount666 = arr5;
        this.drawLineData();
      });
    },
    monthTimer(index, row) {
      console.log(row);
      this.row888 = row;
      this.value00 = this.month;
      timeMonth({
        userId: this.row888.userId,
        time: this.month
      }).then(res => {
        console.log(res);
        this.data8 = res.data;
        let arr1 = [];
        let arr2 = [];
        let arr3 = [];
        let arr4 = [];
        let arr5 = [];
        for (let i = 0; i < this.data8.length; i++) {
          //   arr1.push(this.data8[i].time.slice(8,10));
          arr1.push(this.data8[i].createTime);
          arr2.push(this.data8[i].callAllMinute);
          arr3.push(this.data8[i].callUseMinute);
          arr4.push(this.data8[i].callUseTime);
          arr5.push(this.data8[i].callAllTime);
        }
        this.monthTime666 = arr1;
        this.moneyTime666 = arr2;
        this.callTime666 = arr3;
        this.moneyCount666 = arr4;
        this.callCount666 = arr5;
        this.drawLineData();
      });
      this.dialog8 = true;
      console.log("获取月通话记录");
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams);
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.loadOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(e) {
      console.log(e.id);
      this.queryParams.deptId = e.id;
      this.queryParams.companyId = undefined;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.userName + '"用户吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function() {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        country: "",
        mainBody:"",
        remark: undefined,
        roleIds: [],
        writes: 0
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.companyId = undefined;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      getUser().then(response => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      console.log(9999999,row);
      this.typeModify = type;
      this.reset();
      this.getTreeselect();
        this.getCountryList(row.continent);
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        console.log(888, response);
        this.form = response.data;
        if (this.form.continent) {
          this.form.continent = this.form.continent.split(",");
        }
        if (this.form.country) {
          this.form.country = this.form.country.split(",");
        }
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.form.roleIds = response.roleIds;
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            if (response.code === 200) {
              this.msgSuccess("修改成功，新密码是：" + value);
            }
          });
        })
        .catch(() => {});
    },
    // 解除钉钉绑定
    handleRemove(row) {
      this.$confirm("是否确认解除钉钉绑定?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return removeUser(row.userId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("解除钉钉绑定成功");
        })
        .catch(function() {});
    },
    /** 提交按钮 */
    submitForm: function() {
      if(this.form.businessType==2){
        this.form.country=""
        this.form.continent=''
      }
      console.log(999, this.form.continent);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if( this.form.country){
          this.form.country = this.form.country.toString();
          }
          if(this.form.continent){
          this.form.continent = this.form.continent.toString();
          }
          if(this.form.nickName){
          this.form.nickName = this.form.userName;
          }
          if (this.form.userId != undefined) {
            console.log("正常修改");
            updateUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addUser(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userName || this.ids;
      this.$confirm("是否确认删除用户数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams;
      this.$confirm("是否确认导出今日所有用户拨打统计?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          console.log("123");
          exportUser({
            userName: this.queryParams.userName,
            phonenumber: this.queryParams.phonenumber,
            deptId: this.queryParams.deptId
          }).then(response => {
            console.log(response);
            this.download(response.msg);
          });
        })
        .catch(function() {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style lang="scss">
.btn {
  margin-left: 20px;
}
.red {
  color: #ff0000;
}
.blue {
  color: #409eff;
  cursor: pointer;
}
.yellow {
  color: #f57506ef;
}
.el-dialog__body {
  padding: 20px 50px !important;
}

.layui-progress-bar .el-progress-bar__inner:before {
  content: "";
  width: 100%;
  height: 100%;
  display: block;
  background-image: repeating-linear-gradient(
    -45deg,
    rgba(255, 255, 255, 0.3) 0,
    rgba(255, 255, 255, 0.3) 12.5%,
    transparent 0,
    transparent 25%
  );
  background-size: 80px 80px;
  animation: move 2.5s linear infinite;
}

@keyframes move {
  from {
    background-position: 80px 0;
  }
  to {
    background-position: 0;
  }
}
</style>
<style>
.el-tooltip__popper {
  max-width: 40%;
}
</style>
